package com.xu.t1.service;

import com.xu.t1.mapper.LearningRecordMapper;
import com.xu.t1.model.LearningRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; // Spring 的事务注解
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


/**
 * 负责批量写入学习记录
 *
 * @author xu
 *
 */

@Service
public class LearningRecordTxService {

    private static final Logger logger = LoggerFactory.getLogger(LearningRecordTxService.class);

    @Autowired
    private LearningRecordMapper recordMapper;

    @Transactional
    public boolean saveRecords(List<LearningRecord> records) {
        if (records == null || records.isEmpty()) {
            return false;
        }

        int batchSize = 1000; // 每批插入大小
        int totalRecords = records.size();

        try {
            for (int i = 0; i < totalRecords; i += batchSize) {
                int end = Math.min(i + batchSize, totalRecords);
                List<LearningRecord> batchList = records.subList(i, end);
                int inserted = recordMapper.insertRecords(batchList);
                if (inserted != batchList.size()) {
                    throw new RuntimeException("批量插入失败，预期插入: " + batchList.size() + ", 实际插入: " + inserted);
                }
            }
            return true;
        } catch (Exception e) {
            logger.error("插入学习记录失败，事务将回滚：", e);
            return false;
        }
    }

}